package main

import (
	pb "api-recommend/video"
	"context"
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"google.golang.org/grpc"
	"log"
	"net"
)

type server struct {
	pb.UnimplementedVideoServiceServer
	db *sql.DB
}

func (s *server) GetTopVideos(ctx context.Context, in *pb.TopVideosRequest) (*pb.TopVideosResponse, error) {
	n := in.GetCount()
	userId := in.GetUserId()
	if n == 0 {
		n = 5 // 默认返回前5条记录
	}
	query := `SELECT id, user_id, title, url, like_number FROM video WHERE NOT status = 2 AND video.id NOT IN (SELECT video_id FROM user_video WHERE user_id = ?)ORDER BY like_number DESC LIMIT ?`
	rows, err := s.db.QueryContext(ctx, query, userId, n)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var videos []*pb.Video
	for rows.Next() {
		var videoId, userId, likeNumber int
		var title, url string
		if err := rows.Scan(&videoId, &userId, &title, &url, &likeNumber); err != nil {
			return nil, err
		}
		log.Printf("with id: %d, likenumber: %d", videoId, likeNumber)
		video := &pb.Video{
			Id:         int32(videoId),
			UserId:     int32(userId),
			Title:      title,
			Url:        url,
			LikeNumber: int32(likeNumber),
		}
		fmt.Println(video.GetLikeNumber())
		videos = append(videos, video)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	fmt.Println(videos)
	return &pb.TopVideosResponse{Videos: videos}, nil
}

func main() {
	//nacos配置
	serverConfig := []constant.ServerConfig{
		{
			IpAddr: "58.87.105.2",
			Port:   8848,
		},
	}

	clientConfig := constant.ClientConfig{
		NamespaceId:         "",
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "log",
		CacheDir:            "cache",
		LogLevel:            "debug",
	}

	client, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfig,
		},
	)
	if err != nil {
		fmt.Println("创建 Nacos 客户端失败:", err)
		return
	}

	param := vo.RegisterInstanceParam{
		Ip:          "58.87.105.2",                       // 服务 IP
		Port:        50052,                               // 服务端口
		ServiceName: "api-recommend",                     // 服务名称
		Weight:      1.0,                                 // 权重
		Enable:      true,                                // 是否启用
		Healthy:     true,                                // 是否健康
		Ephemeral:   true,                                // 是否临时实例
		Metadata:    map[string]string{"version": "1.0"}, // 元数据
	}
	success, err := client.RegisterInstance(param)
	if err != nil {
		fmt.Println("注册服务失败:", err)
		return
	}

	if success {
		fmt.Println("服务注册成功")
	} else {
		fmt.Println("服务注册失败")
	}

	dsn := "root:BeiJingJiaoTongDaXue1234567890@tcp(58.87.105.2:3306)/API"

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("Failed to open database: %v", err)
	}
	defer db.Close()
	err = db.Ping()
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	lis, err := net.Listen("tcp", ":50052")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterVideoServiceServer(s, &server{db: db})
	log.Println("Server is listening on port 50052...")
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
